// components/shareImageGenerator/shareImageGenerator.js
var util = require('../../utils/util.js')
var _this
const noteLongTip1 = '长按二维码识别小程序'
const mediaTip1 = '媒体合作伙伴'
const w = 562
const h = 1000
function rpx(n, sizeType){
    if (size === 'save')  {
       return n
  }else {
      return n * system.windowWidth / 750
  }
}

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    action: {
      type: String,
      value: 'none',
      observer: function(newVal, oldVal, changedPath) {
        if (newVal.trim() != oldVal.trim()){
          this.typeDidChanged(newVal)
        }
      }
    },
    fillText: {
      type: String,
      value: 'none'
    },
    noteLongTip: {
      type: String,
      value: noteLongTip1
    },
    mediaTip: {
      type: String,
      value: mediaTip1
    },
    canvasId: {
      type: String,
      value: ''
    },
    imagePath: {
      type: String,
      value: ''
    },
    qrImagePath: {
      type: String,
      value: ''
    },
    genImagePath: {
      type: String,
      value: ''
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    picWidth: 750,
    picHeight: 1334,
    standRadio: 1.0,
    canvasWidth: 750,
    canvasHeight: 1334
  },

  /**
   * 组件的方法列表
   */
  methods: {
    lifetimes: {
      created () {
        _this = this
      },
      detached() {
        // 在组件实例被从页面节点树移除时执行
      },
    },
     typeDidChanged: function(currentValue){
      if (currentValue == 'create') {
        this.start()
      }else if(currentValue == 'save') {
        this.saveImage()
      }
    },
    start: function() {
      _this = this;
      console.log(this.properties.canvasId)
      util.downloadShareBg(this.downloadSuccess, this.downloadFailed)
    },
    saveImage: function() {
      wx.saveImageToPhotosAlbum({
        filePath: _this.data.genImagePath,
        success(res) {
          _this.triggerEvent('saveSuccess', {}, {})
        },
        fail(res) {
          _this.triggerEvent('saveFailed', {}, {})
        }
      })
    },
    downloadSuccess: function(res) {
      _this.properties.imagePath = res.tempFilePath
      wx.getImageInfo({
        src: _this.properties.imagePath,
        success(res) {
          _this.data.picWidth = res.width
          _this.data.picHeight = res.height
          _this.data.standRadio = _this.data.picWidth * 1.0 / _this.data.picHeight
          util.downloadQRImage(_this.downloadQRImageSuccess, _this.downloadFailed)
        }
      })
    },
    downloadQRImageSuccess: function(res) {
      _this.properties.qrImagePath = res.tempFilePath
      _this.prepareForDraw()
      _this.createShareImage()
    },
    downloadFailed: function(res) {
      const data = {}
      const option = {}
      _this.triggerEvent('createFailed', data, option)
    },
    prepareForDraw: function() {
      const system = wx.getSystemInfoSync()
      //缩放比例      
      const systemRadio = system.windowWidth * 1.0 / system.windowHeight
      //系统的屏幕比较瘦，高度以系统屏幕高度为准，比例为图片
      if (_this.data.standRadio < systemRadio) {
        _this.data.canvasHeight = system.windowHeight
        _this.data.canvasWidth = Math.ceil(_this.data.canvasHeight * _this.data.standRadio)

      } else {
        //系统的屏幕比较胖，宽度以系统屏幕宽度为准，比例为图片比例
        _this.data.canvasWidth = system.windowWidth
        _this.data.canvasHeight = Math.ceil(_this.data.canvasWidth / _this.data.standRadio)
      }
      _this.data.scale = _this.data.canvasWidth * 1.0 * system.pixelRatio / _this.data.picWidth


      console.log('canvasWidth' + _this.data.canvasWidth)
      console.log('canvasHeight' + _this.data.canvasHeight)

      _this.setData({
        canvasWidth: _this.data.canvasWidth * 2,
        canvasHeight: _this.data.canvasHeight * 2
      })
      console.log('scale' + _this.data.scale)
    },
    createShareImage: function() {
      const context = wx.createCanvasContext(_this.properties.canvasId,this)
      context.drawImage(this.properties.imagePath, 0, 0, _this.data.canvasWidth, _this.data.canvasHeight)
      this.drawText(context, this.properties.fillText)
      context.drawImage(this.properties.qrImagePath, _this.rem(148), _this.rem(560), _this.rem(80), _this.rem(80))
      //商家合作
      // context.font = 'bold 15px cursive'
      // context.setFontSize(_this.rem(15))
      // context.setFillStyle('black')
      // const oneWidth0 = context.measureText(_this.properties.mediaTip).width
      // context.fillText(_this.properties.mediaTip, Math.ceil((_this.data.canvasWidth - oneWidth0) / 2.0), _this.rem(430))
      //长按二维码提示
      // context.font = 'bold 15px cursive'
      // context.setFontSize(_this.rem(15))
      // context.setFillStyle('black')
      // const oneWidth = context.measureText(_this.properties.noteLongTip).width
      // context.fillText(_this.properties.noteLongTip, Math.ceil((_this.data.canvasWidth - oneWidth) / 2.0), _this.rem(640))
      context.draw(false, function() {
        wx.canvasToTempFilePath({
          canvasId: _this.properties.canvasId,
          destWidth: _this.data.canvasWidth,
          destHeight: _this.data.canvasHeight,
          success(res) {
            context.setGlobalAlpha(0);
            context.fillRect(0, 0, _this.data.canvasWidth, _this.data.canvasHeight);
            context.draw();
            _this.properties.genImagePath = res.tempFilePath
            const data = { 'imageFilePath': _this.properties.genImagePath}
            const option = {}
            _this.triggerEvent('createSuccess', data, option)
          },
          fail(res) {
            console.log(res)

            const data = {}
            const option = {}
            _this.triggerEvent('createFailed', data, option)
          },
          complete() {
          }
        },_this)
      })
    },
    drawText: function(ctx, text) {
      ctx.save()
      const originY = _this.rem(110)
      const originX = [_this.rem(20), _this.rem(20), _this.rem(20), _this.rem(40), _this.rem(60), _this.rem(10)]
      const canvasTotalWidth = _this.data.canvasWidth
      const textHeight = _this.rem(20)
      const lineDistance = _this.rem(5)
      var totalHeight = _this.rem(30)
      var currentLineWidth = 0
      var lineNumber = 0
      var oneOriginX = originX[0]

      for (let i = 0; i < text.length; i++) {
        var one = text[i]
        console.log(one)
        //是数字的样式
        if (_this.isNumber(one)) {
          // ctx.font = 'noraml bold 30px sans-serif'
          ctx.setFontSize(_this.rem(18))
          ctx.setFillStyle('#ff749f')
        } else {
          // ctx.font = 'noraml bold 18px sans-serif'
          ctx.setFontSize(_this.rem(13))
          ctx.setFillStyle('black')
        }
        const oneWidth = ctx.measureText(one).width
        currentLineWidth += oneWidth
        var x, y
        if (oneOriginX + oneOriginX + currentLineWidth < canvasTotalWidth) {
          x = oneOriginX + currentLineWidth - oneWidth
          y = originY + (textHeight + lineDistance) * lineNumber
        } else {
          currentLineWidth = 0
          lineNumber += 1
          oneOriginX = originX[lineNumber]
          x = oneOriginX + currentLineWidth
          y = originY + (textHeight + lineDistance) * lineNumber
          currentLineWidth += oneWidth
        }
        ctx.fillText(one, x, y)

      }
      totalHeight = originY + (textHeight + lineDistance) * lineNumber + originY
      ctx.restore()
    },
    isNumber: function(value) {
      var patrn = /^(-)?\d+(\.\d+)?$/
      if (patrn.exec(value) == null || value == "") {
        return false
      } else {
        return true
      }
    },
      rem: function(n){
      return Math.ceil(n * _this.data.canvasWidth / 375)
    }
  }
})
